import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({
  showSpinner: false
}) // NProgress 配置

const whiteList = ['/login', '/404', '/register', '/resetPaw'] // 不重定向的白名单

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已登录 
  const hasToken = getToken()
  // 判断是否存在token,没有就重新登陆
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    }
    else { //用户登录的同时就已经把角色存入了，直接根据角色生成可达路由即可
      try {
        const roles = store.getters.roles
        // 拿到可达路由
        const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
        // 更新加载路由
        router.options.routes = store.getters.permission_routes
        // 动态添加可访问路由
        router.addRoutes(accessRoutes)
        next()
        NProgress.done() 
      } catch (error) {
        console.info(error)
        // remove token and go to login page to re-login
        await store.dispatch('user/resetToken')
        Message.error(error || 'Has Error')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }
   else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
